package com.xu.controller;

import com.xu.pojo.Books;
import com.xu.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;

/**
 * MVC 一次请求的全过程
 *
 * 1. 用户发起请求
 * 2. 中央控制器 DispatcherServlet
 * 3. DispatcherServlet 调用处理器映射器 HandlerMapping
 * 4. HandlerMapping 找到对应处理器，并返回对应的处理器对象 handler 给中央控制器
 * 5. DispatcherServlet 将 Handler 给 HandlerAdapter 处理器适配器
 * 6. HandlerAdapter 调用 Handler 处理器（controller）
 * 7. Controller调用业务层
 * 8. 业务层调用 Dao 层
 * 9. Dao 层调用 jdbc 或 Mybatis 对数据库操作返回给业务层
 * 10. Controller 得到业务层返回的数据，返回 ModelAndView
 * 11. DispatcherServlet 调用视图解析器 ViewResolve 解析 ModelAndView
 * 12. ViewResolve 返回 view
 * 13. DispatcherServlet 将 view 给 jsp 进行渲染呈现给用户
 *
 */

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    @RequestMapping("/allBook")
    public String list(Model model){
        List<Books> books = bookService.queryAllBook();
        model.addAttribute("books", books);
        return "all_book";
    }

    @RequestMapping("/toAddBook")
    public String toAddPaper(){
        return "add_book";
    }

    @RequestMapping("/addBook")
    public String addPaper(Books books){
        System.out.println(books);
        bookService.addBook(books);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(Model model, int id){
        Books books = bookService.queryBookById(id);
        System.out.println(books);
        model.addAttribute("book", books);
        return "update_book";
    }

    @RequestMapping("/updateBook")
    public String updateBook(Books book){
        System.out.println(book);
        bookService.updateBook(book);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/delete")
    public String deleteBook(int id){
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }

}
